package com.example.demo13.service;


import com.example.demo13.model.Student;
import com.example.demo13.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
@Service
public class StudentServicelmpl implements StudentService{
    @Autowired
    private StudentRepository studentRepository;
    @Override
    public List<Student> findByDeviceType(String stuName ) {
        List<Student> optional = studentRepository.findByDeviceType(stuName);
        return optional;
    }
    @Override
    public List<Student> getAllStudents(){return studentRepository.findAll();}
    @Override
    public void saveStudent(Student student) {
        this.studentRepository.save(student);
    }
    @Override
    public Student getStudentById(long id) {
        Optional<Student> optional = studentRepository.findById(id);
        Student student = null;
        if (optional.isPresent()) {
            student = optional.get();
        }else {
            throw new RuntimeException("找不到学生ID ；；"+id);
        }
        return student;
    }
    @Override
    public void deleteStudentById(long id) {
        this.studentRepository.deleteById(id);
    }
    @Override
    public Page<Student> findPaginated(int pageNo, int pageSize, String sortField, String sortDirection) {
        Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name())
                ? Sort.by(String.valueOf(sortField)).ascending()
                : Sort.by(String.valueOf(sortField)).descending();
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort);
        return this.studentRepository.findAll(pageable);
    }
}
